package com.zhixiang.xaec.action.system;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;

import org.apache.commons.lang.StringUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zhixiang.core.command.QueryFilter;
import com.zhixiang.core.util.AppUtil;
import com.zhixiang.core.util.String2Array;
import com.zhixiang.core.web.action.BaseAction;
import com.zhixiang.xaec.entity.system.FileDetail;
import com.zhixiang.xaec.service.system.FileDetailService;

@Controller
@Scope("prototype")
public class FileDetailAction extends BaseAction
{

    private static final long serialVersionUID = 8709402663321992599L;

    private FileDetail fileDetail;
    
    private Long fileId;
    @Autowired
    private FileDetailService fileDetailService;

    public String list(){
        QueryFilter localQueryFilter = new QueryFilter(getRequest());
        List<FileDetail> list = fileDetailService.getAll(localQueryFilter);
        setTotalCounts(localQueryFilter.getPagingBean().getTotalItems());
        setResult(list);
        return SUCCESS;
    }
    
    public String get(){
        if(this.fileId!=null){
            setResult(fileDetailService.get(this.fileId));
        }
        return SUCCESS;
    }
    
    public String delete(){
        String ids = getRequest().getParameter("ids");
        Long[] l = String2Array.stringToLongArray(ids);
        fileDetailService.remove(l);
        return SUCCESS;
    }
    
    public String save(){
        fileDetailService.save(fileDetail);
        return SUCCESS;
    }
    
    public String fileExists(){
        FileDetail fd =null;
        if(fileDetail!=null && fileDetail.getFileId()!=null){
            fd = fileDetailService.get(fileDetail.getFileId());
            File file = new File((String)AppUtil.getSysConfig().get("uploadDir")+ fd.getFilePath());
            if(!file.exists()){
                setSuccess(false);
            }
        }
        return SUCCESS;
    }
    
    
  public String convertOfficeToPdf(String inputFilePath)
    {
       int num = inputFilePath.lastIndexOf(".");
      String type = inputFilePath.substring(num + 1, inputFilePath.length())
        .toLowerCase();
      System.out.println("officeToPdf文件的格式：" + type);
      if (("doc".equals(type)) || ("docx".equals(type)) || ("ppt".equals(type)) || 
        ("pptx".equals(type)) || ("xls".equals(type)) || 
        ("xlsx".equals(type)) || ("txt".equals(type)) || ("pdf".equals(type)))
      {
        File inputFile = new File(inputFilePath);
        if (inputFile.exists())
        {
          DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();

          String officeHome = getOfficeHome();
          config.setOfficeHome(officeHome);

          OfficeManager officeManager = config.buildOfficeManager();
          officeManager.start();

          OfficeDocumentConverter converter = new OfficeDocumentConverter(
            officeManager);
          String outputFilePath = getOutputFilePath(inputFilePath, "pdf");

          File outputFile = new File(outputFilePath);
          if (!outputFile.getParentFile().exists())
          {
            outputFile.getParentFile().mkdirs();
          }
          converter.convert(inputFile, outputFile);
          officeManager.stop();
          return outputFilePath;
        }

        System.out.println("对不起，源文件不存在，OpenOffice转换失败！");
        return "";
      }

      System.out.println("对不起，OpenOffice只能把Office相关文件格式转换成Pdf格式，转换失败！");
      return "";
    }

    private String convertPdfToSwf(String sourceFile)
    {
      int num = sourceFile.lastIndexOf(".");
      String type = sourceFile.substring(num + 1, sourceFile.length())
        .toLowerCase();
      System.out.println("convertPdf2Swf文件的格式：" + type);
      if ("pdf".equals(type))
      {
        File file = new File(sourceFile);
        if (file.exists())
        {
          String pdfToSwfHome = getPdfToSwfHome();
          String outFile = getOutputFilePath(sourceFile, "swf");
          String command = pdfToSwfHome + "/pdf2swf.exe \"" + sourceFile + "\" -o  \"" + outFile + "\" -s flashversion=9 ";
          try
          {
            System.out.println(command);
            Process process = Runtime.getRuntime().exec(command);

            StreamGobbler sg1 = new StreamGobbler(process.getInputStream(), "Console");
            StreamGobbler sg2 = new StreamGobbler(process.getErrorStream(), "Error");
            sg1.start();
            sg2.start();
            try
            {
              process.waitFor();
            }
            catch (InterruptedException e) {
              e.printStackTrace();
              System.out.println("###--Msg: swf 转换过程出错！");
            }
            File swfFile = new File(outFile);
            if (swfFile.exists()) {
              if (process != null) {
                process.destroy();
              }
              System.out.println("###--Msg: swf 转换成功:" + outFile);
              return outFile;
            }
            return "";
          }
          catch (Exception e) {
            e.printStackTrace();
            System.out.println("###--Msg: swf 转换失败");

            return "";
          }
        }
        System.out.println("对不起，源文件不存在，swftools转换失败！");
        return "";
      }

      System.out.println("对不起，swftools只能把Pdf格式转换成Swf格式，转换失败！");
      return "";
    }

    public String getOutputFilePath(String inputFilePath, String type)
    {
      String outputFilePath = "";
      int num = inputFilePath.lastIndexOf(".");
      if (num > 0)
      {
        outputFilePath = inputFilePath.substring(0, num) + "." + type;
      }
      else {
        outputFilePath = inputFilePath + "." + type;
      }
      return outputFilePath;
    }

    public String getOfficeHome()
    {
      String osName = System.getProperty("os.name").toLowerCase();
      InputStream in = getClass().getClassLoader().getResourceAsStream("conf/jdbc.properties");
      Properties p = new Properties();
      try {
        p.load(in);
        String name = p.getProperty("windows.officeToPdf");
        System.out.println("windowspdf:" + name);
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (Pattern.matches("linux.*", osName))
      {
        return "/opt/openoffice.org3";
      }if (Pattern.matches("windows.*", osName))
      {
        return p.getProperty("windows.officeToPdf");
      }
      if (Pattern.matches("mac.*", osName))
      {
        return "/Application/OpenOffice.org.app/Contents";
      }
      return null;
    }

    public String getPdfToSwfHome()
    {
      String osName = System.getProperty("os.name").toLowerCase();
      InputStream in = getClass().getClassLoader().getResourceAsStream("conf/jdbc.properties");
      Properties p = new Properties();
      try {
        p.load(in);
        String name = p.getProperty("windows.pdfToSwf");
        System.out.println("windowsSwf:" + name);
      }
      catch (IOException e) {
        e.printStackTrace();
      }
      if (Pattern.matches("linux.*", osName))
      {
        return "/opt/SWFTools";
      }if (Pattern.matches("windows.*", osName))
      {
        return p.getProperty("windows.pdfToSwf");
      }
      if (Pattern.matches("mac.*", osName))
      {
        return "/Application/SWFTools.app/Contents";
      }
      return null;
    }

    public String docToSwf()
    {
      String fileId = getRequest().getParameter("fileId");
      String mark = "no";
      if (StringUtils.isNotEmpty(fileId))
      {
        FileDetail fileDetail = fileDetailService.get(new Long(fileId));
        String swfUrl = getOutputFilePath(fileDetail.getFilePath(), "swf");
        getRequest().setAttribute("swfPath", swfUrl);
        getRequest().setAttribute("fileId", fileId);
        String path = (String)AppUtil.getSysConfig().get(
            "uploadDir") + fileDetail.getFilePath();
        path = path.replace("\\", "/");
        String swfPath = getOutputFilePath(path, "swf");
        File file = new File(swfPath);
        if (file.exists())
        {
          mark = "yes";
        } else {
          file = new File(path);
          if (file.exists())
          {
            int num = path.lastIndexOf(".");
            String pdfPath = "";
            if ("pdf".equals(path.substring(num + 1, path.length()).toLowerCase())) {
              pdfPath = path;
            } else {
              pdfPath = getOutputFilePath(path, "pdf");
              file = new File(pdfPath);
              if (!file.exists())
              {
                pdfPath = convertOfficeToPdf(path);
              }
            }
            swfPath = convertPdfToSwf(pdfPath);
            if (StringUtils.isNotEmpty(swfPath))
            {
              if (!"pdf".equals(path.substring(num + 1, path.length()).toLowerCase())) {
                File filePdf = new File(pdfPath);
                filePdf.delete();
              }
              mark = "yes";
            }
          } else {
            System.out.println("对不起，源文件不存在！" + path);
          }
        }
      }
      getRequest().setAttribute("mark", mark);
      return "fileShow";
    }

    public class StreamGobbler extends Thread
    {
      InputStream is;
      String type;

      StreamGobbler(InputStream is, String type)
      {
        this.is = is;
        this.type = type;
      }

      public void run()
      {
        BufferedReader br = null;
        try
        {
          InputStreamReader isr = new InputStreamReader(this.is);
          br = new BufferedReader(isr);
          @SuppressWarnings("unused")
          String line = null;
          while ((line = br.readLine()) != null);
        }
        catch (IOException ioe) {
          ioe.printStackTrace();

          if (br != null)
          {
            try
            {
              br.close();
            }
            catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        finally
        {
          if (br != null)
          {
            try
            {
              br.close();
            }
            catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    
    public void showFile(){
        String fileId = getRequest().getParameter("fileId");
        FileDetail fileDetail = fileDetailService.get(new Long(fileId));
        String path = (String)AppUtil.getSysConfig().get(
            "uploadDir") + getOutputFilePath(fileDetail.getFilePath(), "swf");
        ServletOutputStream localServletOutputStream = null;
        FileInputStream localFileInputStream = null;
        try
        {
            localFileInputStream = new FileInputStream(path);

            localServletOutputStream = getResponse().getOutputStream();
            byte[] arrayOfByte = new byte[1024];
            for (int i = localFileInputStream.read(arrayOfByte); i > 0; i = localFileInputStream.read(arrayOfByte))
            {
                localServletOutputStream.write(arrayOfByte, 0, i);
            }
        }
        catch (Exception localException)
        {
            localException.printStackTrace();
        }
        finally
        {
            if (localServletOutputStream != null)
            {
                try
                {
                    localFileInputStream.close();
                    localServletOutputStream.flush();
                    localServletOutputStream.close();
                }
                catch (IOException localIOException5)
                {
                    localIOException5.printStackTrace();
                }
            }
        }
    }
    
    public FileDetail getFileDetail()
    {
        return fileDetail;
    }

    public void setFileDetail(FileDetail fileDetail)
    {
        this.fileDetail = fileDetail;
    }

    public Long getFileId()
    {
        return fileId;
    }

    public void setFileId(Long fileId)
    {
        this.fileId = fileId;
    }
    
    
    
}
